<template>
  <div class="container">
    <editPageNew
      ref="editPage"
      :rightBtnArr="rightBtnArr"
      :stepConfig="stepConfig"
      :creatInfo="creatInfo"
      :moreBtnArr="moreBtnArr"
      :showMore="pageType != 'add'"
      showTopTitle
    >
      <template slot="editPageTitle">
        <span class="title-code">{{
          `检修计划包 ${formData.code || ""}`
        }}</span>
      </template>
      <div class="plan-title">
        <div v-show="!showInput" class="name">
          <span style="color: red"></span>
          <span>{{ titleName }}</span>
          <el-link
            v-show="titleEdit"
            style="font-size: 20px"
            icon="el-icon-edit-outline"
            @click="editTitle"
          ></el-link>
        </div>
        <div v-show="showInput" class="name-input">
          <!-- <label>参数组名称</label> -->
          <el-input
            type="text"
            v-model="titleName"
            maxlength="64"
            show-word-limit
            @blur="loseFocus"
            placeholder="请输入名称"
            clearable
            ref="mark"
            ><template slot="prepend"
              >名称</template
            ></el-input
          >
        </div>
      </div>
      <el-collapse v-model="activeNames" style="padding-right: 10px">
        <el-collapse-item name="1">
          <template slot="title"> 基本信息 </template>
          <addBasicInfo
            v-show="status < 2"
            ref="addBasicInfo"
            :planList="formData.depts"
            :isCreateUser="isCreateUser"
            :status="status"
          ></addBasicInfo>
          <basicInfoDetail
            v-if="status > 1"
            :planList="formData.depts"
            :status="status"
          ></basicInfoDetail>
        </el-collapse-item>
        <el-collapse-item name="2" v-if="status > 0">
          <template slot="title"> 审批信息 </template>
          <workFlow
            :isDetails="pageType == 'query'"
            :currentFlowData="formData"
            ref="workFlow"
            @submitSuccess="workFlowSuccess"
          ></workFlow>
        </el-collapse-item>
      </el-collapse>
    </editPageNew>
    <dialogPublic
      title="提交"
      :show.sync="show"
      @doClose="() => (show = false)"
      :fullscreen="true"
      :noFootBtn="true"
      appendTobody
    >
      <workFlow
        v-if="show"
        :isDetails="pageType == 'query'"
        workflowCode="repair_plan_package"
        :currentFlowData="formData"
        :beforeSubmit="beforeSubmit"
        ref="workFlow"
        @submitSuccess="workFlowInitSuccess"
      ></workFlow>
    </dialogPublic>
  </div>
</template>
<script>
import {
  queryPlanPackageDetail,
  addOrUpdatePlanPackage,
  deletePlanPackage,
} from "@/api/productionPlan/overhaulPlanPackage.js";
import addBasicInfo from "./addBasicInfo.vue";
import basicInfoDetail from "./basicInfoDetail.vue";
export default {
  components: {
    addBasicInfo,
    basicInfoDetail,
  },
  data() {
    return {
      titleName: "",
      showInput: false,
      titleEdit: true,
      show: false,
      activeNames: ["1", "2"],
      status: -1,
      pageType: "",
      formData: {},
      creatInfo: {},
      moreBtnArr: [
        {
          text: "操作记录",
          methods: () => {
            this.$refs.editPage.showOperate();
          },
        },
      ],
      beforeSubmit: {
        methods: (data) => {
          return new Promise((resolve, reject) => {
            try {
              let params = Object.assign({}, this.formData);
              params.name = this.titleName;
              let data = this.$refs.addBasicInfo.getPlanData();
              params.depts = data;
              this.formData = params;
              resolve(params);
            } catch (error) {
              reject(error);
            }
          });
        },
      },
      isDutyUnit: false,
    };
  },
  computed: {
    rightBtnArr() {
      let arr = [
        {
          text: "提交",
          icon: "el-icon-video-play",
          hide:
            ["details", "perform", "add"].includes(this.pageType) ||
            this.status != 0,
          content: !this.$store.getters.isBtnAuth("doSubmit")
            ? "未授权的功能"
            : "非创建人无法提交",
          disabled:
            !this.$store.getters.isBtnAuth("doSubmit") || !this.isCreateUser,
          methods: () => {
            this.show = true;
          },
        },
        {
          text: "保存",
          icon: "el-icon-check",
          hide:
            ["details", "perform"].includes(this.pageType) || this.status > 0,
          content: !this.$store.getters.isBtnAuth("save")
            ? "未授权的功能"
            : "非创建人或责任单位下人员无法保存",
          disabled:
            !this.$store.getters.isBtnAuth("save") ||
            (!this.isCreateUser && !this.isDutyUnit),
          methods: () => {
            this.save();
          },
        },
        {
          text: "删除",
          icon: "el-icon-delete-solid",
          hide:
            ["perform", "details", "add"].includes(this.pageType) ||
            this.status != 0,
          content: !this.$store.getters.isBtnAuth("doSubmit")
            ? "未授权的功能"
            : "非创建人无法删除",
          disabled:
            !this.$store.getters.isBtnAuth("delete") || !this.isCreateUser,
          methods: () => {
            this.deleteId();
          },
        },
      ];
      return arr;
    },
    stepConfig() {
      let obj = {
        nowStep: this.status, //当前步骤，对应stepItem数组的下标，例如：0-步骤一、1-步骤二
        stepItem: ["草稿", "待审核", "审核完成", "执行中", "已完成"],
      };
      return obj;
    },
    isAddOredit() {
      return this.pageType == "add" || [0, 1].includes(this.status);
    },
    unChangeable() {
      return ["query", "detail"].includes(this.pageType) || this.status == 1;
    },
    isCreateUser() {
      return (
        this.pageType == "add" ||
        this.formData.createBy == this.$store.getters.userInfo.id
      );
    },
  },
  created() {
    this.init();
  },
  mounted() {},
  methods: {
    init() {
      let { id, pageType } = this.$route.query;
      if (id) {
        this.pageType = this.$store.getters.isBtnAuth("edit")
          ? "edit"
          : "detail";
        this.getDetails(id);
        if (this.pageType == "detail") {
          this.titleEdit = false;
        }
      } else {
        this.pageType = "add";
        this.showInput = true;
      }
      if (["query", "detail"].includes(pageType) || this.status == 1) {
        this.basicConfig.itemArr.map((i) => (i.disabled = true));
      }
    },
    //编辑标题
    editTitle() {
      this.showInput = true;
      setTimeout(() => {
        this.$refs.mark.focus();
      }, 0);
    },
    //标题输入框失去焦点
    loseFocus() {
      if (this.titleName != "") {
        this.showInput = false;
      } else {
        this.showInput = true;
        this.$message.warning("标题不能为空");
      }
    },
    //获取检修计划包详情
    getDetails(id) {
      queryPlanPackageDetail({ id: id }).then((res) => {
        if (res.code == 200) {
          this.formData = res.data;
          if (this.formData.depts.length > 0) {
            this.formData.deptManage = this.formData.depts[0].deptId;
            this.formData.deptManageName = this.formData.depts[0].deptName;
          }
          this.creatInfo = res.data;
          this.status = this.formData.status;
          this.titleName = this.formData.name;
          this.formData.depts.forEach((item, index) => {
            if (item.deptId == this.$store.getters.currentOrgInfo.id) {
              this.isDutyUnit = true;
            }
          });
          if (this.status != 0) {
            this.titleEdit = false;
          } else {
            this.titleEdit = true;
          }
          if (this.status > 1) {
            this.activeNames = ["1"];
          }
        }
      });
    },
    //删除维保计划
    deleteId() {
      this.$confirm("确定要删除选中数据吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deletePlanPackage({ packageId: this.formData.id }).then((res) => {
            if (res.code === 200) {
              this.$message.success(res.description);
              this.$utils.addOperateLog(this.formData.id, "删除了检修计划包");
              this.updateListData();
              this.$refs.editPage.closePage();
            }
          });
        })
        .catch((e) => {});
    },
    //保存正常维护标准
    save() {
      let params = Object.assign({}, this.formData);
      params.name = this.titleName;
      if (this.titleName == "") {
        this.loseFocus();
      } else {
        let data = this.$refs.addBasicInfo.getPlanData();
        params.depts = data;
        addOrUpdatePlanPackage(params).then((res) => {
          if (res.code == 200) {
            this.$message.success(res.description);
            if (this.pageType == "add") {
              this.$utils.addOperateLog(res.data.id, "新建了检修计划包");
              this.updateListData();
              let obj = {
                id: res.data.id,
                pageType: "edit",
              };
              this.$router.push({
                query: obj,
              });
            } else {
              this.$utils.addOperateLog(this.formData.id, "修改了检修计划包");
              this.getDetails(this.formData.id);
              this.updateListData();
            }
          }
        });
      }
    },
    updateListData() {
      /* 通过localStorage来实现浏览器不同窗口之间的通信 */
      let num = Math.floor(Math.random() * 1000) + 1; //产生随机数，保证每次的值都不一样
      localStorage.setItem("update", num); //设置localStorage里面的值，保证每次都会触发storage事件
    },
    //工作流提交成功之后
    workFlowSuccess() {
      this.updateListData();
      this.getDetails(this.formData.id);
      this.$refs.workFlow.initIframe();
    },
    //草稿状态工作流提交成功之后
    workFlowInitSuccess() {
      this.show = false;
      this.$utils.addOperateLog(this.formData.id, "提交了检修计划包");
      this.updateListData();
      this.getDetails(this.formData.id);
    },
  },
};
</script>
<style lang="less" scoped>
.container {
  height: 100%;
  width: 100%;
  overflow: hidden;
  background-color: #ffffff;
  .TitleImg {
    margin-right: 2px;
    font-size: 22px;
  }
  .plan-title {
    height: 40px;
    margin: 0 0 10px 0;
    .name {
      font-size: 18px;
      padding: 0 10px;
      height: 40px;
      font-weight: bold;
      line-height: 40px;
      text-align: left;
      padding: 0 10px;
    }
    .name-input {
      width: 400px;
      height: 40px;
      line-height: 40px;
    }
  }
}
</style>